package com.vc.opengl;

import java.lang.ref.WeakReference;

import android.annotation.SuppressLint;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;

/**
 * OpenGL绘制所在的容器
 * @author Administrator
 *
 */
@SuppressLint({"InlinedApi"})
public class GLView extends GLSurfaceView
{
  static String TAG = "GLView";

  public boolean m_bStartPaint = false;
  
  public int m_nglVersion = 1;
  
  WeakReference<GLRender> glRender;
  
  public GLView(Context context)
  {
    super(context);
    this.m_nglVersion = GLRender.getGLVersion(context);
    Log.d(TAG, "opengl version = " + this.m_nglVersion);
    init(false, 0, 0);
  }

  @SuppressLint({"NewApi"})
  public GLView(Context context, AttributeSet attrs)
  {
    super(context, attrs);
    this.m_nglVersion = GLRender.getGLVersion(context);
    init(false, 0, 0);
    Log.d(TAG, "opengl version == " + this.m_nglVersion);
  }

  public void setRenderer(GLRender render)
  {
    this.glRender = new WeakReference<GLRender>(render);
    super.setRenderer(render);
  }

  public void surfaceDestroyed(SurfaceHolder holder)
  {
    Log.d(TAG, "surfaceDestroyed");
    this.glRender.get().onSurfaceDestroyed();
    super.surfaceDestroyed(holder);
  }

  public void onPause() {
    Log.d(TAG, "onPause");
    this.glRender.get().onPause();
    super.onPause();
  }

  public void onResume() {
    Log.d(TAG, "onResume");
    this.glRender.get().onResume();
    super.onResume();
  }

  public void onRequestRender() {
	this.m_bStartPaint = true;
    super.requestRender();
  }

  public void surfaceCreated(SurfaceHolder holder) {
    super.surfaceCreated(holder);
    this.glRender.get().surfaceCreated(holder);
    Log.d(TAG, "surfaceCreated");
  }

  private void init(boolean translucent, int depth, int stencil) {
    SurfaceHolder holder = getHolder();
    holder.addCallback(this);

    if (this.m_nglVersion == 2) {
      setEGLContextFactory(new ContextFactory());
      setEGLConfigChooser(new ConfigChooser(5, 6, 5, 0, 0, 0));
    }
    Log.d(TAG, "init GLVideoView");
  }

  void setMeasuredDimensionex(int w, int h) {
    super.setMeasuredDimension(w, h);
  }
}